if CLIENT then return end

-- Checks to see if the database exists
function LeaderBoardCheck(ply)
timer.Simple( 1, function()
if sql.TableExists("TDM_Leaderboards_ScoreV9") then
	--	MsgN("[TDM LEADERBOARDS DB] Table Already Exists")
	else
		if (!sql.TableExists("TDM_Leaderboards_ScoreV9")) then
			local Query = "CREATE TABLE TDM_Leaderboards_ScoreV9 ( UniqueID varchar(255), Name varchar(255), Kills varchar(255), Deaths varchar(255) )"
			local Result = sql.Query(Query)
			if (sql.TableExists("TDM_Leaderboards_ScoreV9")) then
	--			MsgN("[TDM LEADERBOARDS DB] Successfully created TDM_Leaderboards_ScoreV9")
			else
	--			MsgN("[TDM LEADERBOARDS DB] Somthing went wrong with the TDM_Leaderboards_ScoreV9 query!")
	--			MsgN( sql.LastError( Result ) )
			end	
		end
end
OutWithTheOld()
AddPlayerLBDB(ply)
end)
end
hook.Add( "PlayerInitialSpawn", "LeaderBoardCheck", LeaderBoardCheck )


-- Old System Exists, Time to Convert
function OutWithTheOld()
if (file.Exists("TDM/leaderboards/users.txt","DATA")) then
    local data = file.Read("TDM/leaderboards/users.txt","DATA")
    local lines = string.Explode("\n",data)
    if not(#lines > 0) then return end
    for i, line in ipairs(lines) do
        if line == "" then
			break
        end
        local info = string.Explode(",",line)
        local UniqueID = info[1]
        local plyName = info[4]
        local kills = info[2]
        local deaths = info[3]
		local RemoveTilda = string.gsub(plyName,"'"," ")
		local RemoveComma = string.gsub(RemoveTilda,","," ")
		local RemoveSQ = string.gsub(RemoveComma,"'"," ")
		RemoveDQ = string.gsub(RemoveSQ,'"',' ')
		local DoesExist = sql.QueryValue( "SELECT UniqueID FROM TDM_Leaderboards_ScoreV9 WHERE UniqueID = '"..UniqueID.."'" )
		if DoesExist != nil then
			MsgN("Player: "..RemoveDQ.." already exists.")
		else
			MsgN("Player: "..RemoveDQ.." did not exist in the database, adding him now!")
			sql.Query( "INSERT INTO TDM_Leaderboards_ScoreV9 (`UniqueID`, `Name`, `Kills`, `Deaths`) VALUES ('"..UniqueID.."', '"..RemoveDQ.."', '"..kills.."', '"..deaths.."')" )
		end
    end
	local BackTDMFile = file.Read("TDM/leaderboards/users.txt")
	file.Write("TDM/leaderboards/backup_users.txt", BackTDMFile)
	MsgN("[TDM] Players have been added to the database.")
	MsgN("[TDM] We shall backup the old users.txt and call it backup_users.txt")
	MsgN("[TDM] Now that the backup is completed, we shall delete the original users.txt")
	file.Delete("TDM/leaderboards/users.txt")
end
end


-- Adds Player to the Database
function AddPlayerLBDB(ply)
		local NickName = ply:Nick()
		local PUniqueID = ply:UniqueID()
		local Result = sql.Query( "SELECT UniqueID, Name, Kills, Deaths FROM TDM_Leaderboards_ScoreV9 WHERE UniqueID = '"..PUniqueID.."'" )
		if (!Result) then
		sql.Query( "INSERT INTO TDM_Leaderboards_ScoreV9 (`UniqueID`, `Name`, `Kills`, `Deaths`) VALUES ('"..PUniqueID.."', '"..NickName.."', '0','0')" )
			MsgN("[TDM] Player "..NickName.." was added to the database with UniqueID "..PUniqueID.."")
		else
			MsgN("[TDM] Player "..NickName.." is already part of the database")
	    sql.Query("UPDATE TDM_Leaderboards_ScoreV9 SET Name = '"..NickName.."' WHERE UniqueID = '"..PUniqueID.."'")
		local Result1 = sql.QueryValue( "SELECT UniqueID FROM TDM_Leaderboards_ScoreV9 WHERE UniqueID = '"..PUniqueID.."'" )
		local Result2 = sql.QueryValue( "SELECT Name FROM TDM_Leaderboards_ScoreV9 WHERE UniqueID = '"..PUniqueID.."'" )
		local Result3 = sql.QueryValue( "SELECT Kills FROM TDM_Leaderboards_ScoreV9 WHERE UniqueID = '"..PUniqueID.."'" )
		local Result4 = sql.QueryValue( "SELECT Deaths FROM TDM_Leaderboards_ScoreV9 WHERE UniqueID = '"..PUniqueID.."'" )
	--	MsgN("UniqueID: "..Result1)
	--	MsgN("PlayerName: "..Result2)
	--	MsgN("Kills: "..Result3)
	--	MsgN("Deaths: "..Result4)
		end
end


-- Adds Kills/Deaths to the database
function PlayerDeathGoalTDMLB( ply, wep, killer )
if ply:Team() != killer:Team() || killer == ply then
local OldKills = sql.QueryValue( "SELECT Kills FROM TDM_Leaderboards_ScoreV9 WHERE UniqueID = '"..killer:UniqueID().."'" )
local OldDeaths = sql.QueryValue( "SELECT Deaths FROM TDM_Leaderboards_ScoreV9 WHERE UniqueID = '"..ply:UniqueID().."'" )
local NewKills = OldKills + 1 
local NewDeaths = OldDeaths + 1 
--MsgN('Player '..killer:Nick()..' kills are: '..NewKills)
--MsgN('Player '..ply:Nick()..' deaths are: '..NewDeaths)
sql.Query("UPDATE TDM_Leaderboards_ScoreV9 SET Kills = '"..NewKills.."' WHERE UniqueID = '"..killer:UniqueID().."'")
sql.Query("UPDATE TDM_Leaderboards_ScoreV9 SET Deaths = '"..NewDeaths.."' WHERE UniqueID = '"..ply:UniqueID().."'")
end

if ply:Team() == killer:Team() then 
end

end
hook.Add( "PlayerDeath", "PlayerDeathGoalTDMLB", PlayerDeathGoalTDMLB ) 


-- Player requested leaderboard status
function ShowLB(ply)
	umsg.Start("LeaderboardsLB",ply)
	umsg.End()

	local GetData = sql.Query( "SELECT * FROM TDM_Leaderboards_ScoreV9 ORDER BY Kills DESC LIMIT 100" )
	for k,v in pairs(GetData) do
	--	MsgN("--LINE BREAK--")
	--	MsgN(v.Name)
	--	MsgN(v.UniqueID)
	--	MsgN(v.Kills)
	--	MsgN(v.Deaths)
		local kd = v.Kills/v.Deaths
	
		umsg.Start("LBData",ply)
		umsg.String(v.Name)
		umsg.Short(v.Kills)
		umsg.Short(v.Deaths)
		umsg.Float(kd)
		umsg.End()
--	if(k == 100) then break end
	end
	--MsgN("--LINE BREAK--")
end


	

-- Player requested rank status
function ShowRankLB(ply)
local GetData = sql.Query( "SELECT * FROM TDM_Leaderboards_ScoreV5" )
for k,v in pairs(GetData) do
	k2 = k
end
GetPlayerKills = sql.QueryValue( "SELECT Kills FROM TDM_Leaderboards_ScoreV5 WHERE UniqueID = '"..ply:UniqueID().."'")
GetOtherKills = sql.Query( "SELECT Kills FROM TDM_Leaderboards_ScoreV5 WHERE UniqueID != '"..ply:UniqueID().."'")
local rank = 1
for k,v in pairs(GetOtherKills) do
    if v['Kills'] > GetPlayerKills then rank = rank + 1 end
end
umsg.Start("RankLB",ply)
    umsg.Short(rank)
    umsg.Short(k2)
umsg.End()
end




-- Player is requesting something
function CheckSaidLB(ply,said)
	local words = string.Explode(" ", said)
	if words[1] == "!lbs" or words[1] == "!leaderboards" then
		ShowLB(ply)
	end
	if words[1] == "!rank" then
		ShowRankLB(ply)
	end
end
hook.Add("PlayerSay","CheckSaidLB",CheckSaidLB)